package net.loststone

class TodoController {

    def authenticationService

    static allowedMethods = [save: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def onlyLoggedInUsers = {
        if (!authenticationService.isLoggedIn(request)) {
            // Redirect or return Forbidden
            response.sendError(403)
        }
    }
    
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        params.sort = "done";
        params.order = "desc";
        [todoInstanceList: Todo.list(params), todoInstanceTotal: Todo.count()]
    }

    def create = {
        // Forbid non-admin users to create TODOs
        onlyLoggedInUsers();

        def todoInstance = new Todo()
        todoInstance.properties = params
        return [todoInstance: todoInstance]
    }

    def save = {
        def todoInstance = new Todo(params)
        if (todoInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'todo.label', default: 'Todo'), todoInstance.id])}"
            redirect(action: "list")
        }
        else {
            render(view: "create", model: [todoInstance: todoInstance])
        }
    }

    def show = {
        def todoInstance = Todo.get(params.id)
        if (!todoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'todo.label', default: 'Todo'), params.id])}"
            redirect(action: "list")
        }
        else {
            [todoInstance: todoInstance]
        }
    }

}
